package com.itheima.mobile.service.impl;

import com.itheima.common.entity.Result;
import com.itheima.mobile.dto.OrderDto;
import com.itheima.mobile.mapper.MemberDao;
import com.itheima.mobile.mapper.OrderDao;
import com.itheima.mobile.mapper.OrderSettingDao;
import com.itheima.mobile.mapper.SetmealDao;
import com.itheima.mobile.pojo.Member;
import com.itheima.mobile.pojo.Order;
import com.itheima.mobile.pojo.OrderSetting;
import com.itheima.mobile.pojo.Setmeal;
import com.itheima.mobile.service.IOrderService;
import com.itheima.mobile.vo.OrderVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;

@Service
public class IOrderServiceImpl implements IOrderService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private SetmealDao setmealDao;

    /**
     * 提交订单
     *
     * @param orderDto
     * @return
     */
    @Override
    @Transactional
    public Result submitOrder(OrderDto orderDto) {
        if (orderDto.getName() == null || orderDto.getName().equals("")) {
            return Result.of(false, "姓名不能为空!", null);
        }

        if (orderDto.getTelephone() == null || orderDto.getTelephone().equals("")) {
            return Result.of(false, "电话不能为空!", null);
        }

        if (orderDto.getValidateCode() == null || orderDto.getValidateCode().equals("")) {
            return Result.of(false, "验证码不能为空!", null);
        }

        if (orderDto.getOrderDate() == null) {
            return Result.of(false, "日期不能为空!", null);
        }

        //校验验证码
        String validateCode = redisTemplate.opsForValue().get(orderDto.getTelephone());

        if (!orderDto.getValidateCode().equals(validateCode)) {
            return Result.of(false, "验证码错误!", null);
        }

        Date orderDate = orderDto.getOrderDate();
        String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(orderDate);
        //检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        OrderSetting orderSetting = orderSettingDao.getOrderSettingByDate(dateStr);
        if (orderSetting == null) {
            return Result.of(false, "医生未设置预约信息，无法预约!", null);
        }

        if (orderSetting.getReservations() >= orderSetting.getNumber()) {
            return Result.of(false, "已超过当天预约上限，无法预约!", null);
        }

        //检查当前用户如不是会员，需要自动完成注册

        Member member = memberDao.getMemberByPhone(orderDto.getTelephone());
        if (member == null) {
            //不是会员，自动注册
            member = new Member();
            member.setName(orderDto.getName());
            member.setIdCard(orderDto.getIdCard());
            member.setPhoneNumber(orderDto.getTelephone());
            member.setSex(orderDto.getSex());
            member.setRegTime(new Date());
            memberDao.add(member);
        } else {
            //是会员
            //检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
            Order order = orderDao.getOrderByPhoneAndDateAndSetmealId(orderDto.getTelephone(), dateStr, orderDto.getSetmealId().toString());

            if (order != null) {
                return Result.of(false, "您当天该套餐已有预约!", null);
            }
        }

        //保存预约信息
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(orderDto.getOrderDate());
        order.setOrderStatus("未到诊");
        order.setOrderType("微信预约");
        order.setSetmealId(orderDto.getSetmealId());
        orderDao.save(order);

        //更新已预约人数
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.updateById(orderSetting);


        return Result.of(true, "预约成功!", order.getId());
    }

    /**
     * 根据id查询订单
     *
     * @param id
     * @return
     */
    @Override
    public Result findById(String id) {
        Order order = orderDao.findById(id);
        if (order == null) {
            return Result.of(false, "查询预约信息失败!", null);
        }

        String memberId = order.getMemberId().toString();
        String setmealId = order.getSetmealId().toString();

        //查询会员信息
        Member member = memberDao.getById(memberId);
        //查询套餐信息
        String setmealName = setmealDao.findSetmealNameById(setmealId);
        //封装返回
        OrderVo orderVo = new OrderVo();
        orderVo.setOrderDate(new SimpleDateFormat("yyyy-MM-dd").format(order.getOrderDate()));
        orderVo.setOrderType(order.getOrderType());
        orderVo.setMember(member.getName());
        orderVo.setSetmeal(setmealName);

        return Result.of(true, "查询预约信息成功!", orderVo);
    }
}
